package research.sbookmarking.output;

import java.util.*;
import java.io.*;

public class OutputStreamFactory {

	private HashMap<String,Object> factory = new HashMap<String,Object>();
	
	private static OutputStreamFactory anInstance = null;
	
	public OutputStreamFactory () {
		
	}
	
	public final void addStream(String filename, Object outputStream) {
		factory.put (filename,outputStream);
	}

	protected OutputStream openOutputStream (String filename, boolean append){
		try {
			return new BufferedOutputStream( new FileOutputStream(filename,append));
		}
		catch (IOException e){
			throw new RuntimeException(e);
		}
	}
	
	protected OutputStream createOutputStream(String filename, boolean append) {
		return openOutputStream(filename,append);
	}

	public PrintWriter getFileWriter (String filename, boolean append) {
		try {
			PrintWriter file = (PrintWriter)factory.get(filename);

			if(factory.get(filename)==null){
				OutputStreamWriter out = new OutputStreamWriter (getOutputStream(filename,append),"UTF-8");
				file= new PrintWriter (out);
			}
		
			return file;
		}
		catch (IOException e){
			throw new RuntimeException(e);
		}
	}

	public OutputStream getOutputStream(String filename, boolean append) {
		OutputStream os;
		
		if (factory.containsKey(filename) && factory.get(filename)!=null){
			os = (OutputStream)factory.get(filename);
		}
		else {
			os = createOutputStream(filename,append);
		}
		
		return os;
	}
	
	public Object getStream(String filename){
		Object stream = factory.get(filename); 

		if (stream==null){
			throw new NullPointerException ("The link to the file, "+filename +", has disappeared");
		}
		
		return stream;
	}
	
	public void removeStream(String filename){
		factory.remove(filename);
	}
	
	public static OutputStreamFactory getInstance(){
		if (anInstance==null){
			anInstance = new OutputStreamFactory();
		}
		
		return anInstance;
	}
}
